/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function(k, nums) {
  this.arr = nums.sort((a, b) => a - b);
  this.k = k;
};

/**
 * @param {number} val
 * @return {number}
 */
KthLargest.prototype.add = function(val) {
  // console.log("前", [...this.arr]);
  for(let i = 0; i < this.arr.length; i++) {
    if(val < this.arr[i]) {
      this.arr.splice(i, 1, val, this.arr[i]);
      break;
    }
    if(i == this.arr.length - 1) {
      this.arr[this.arr.length] = val;
      break;
    }
  }
  if(!this.arr.length) {
    this.arr.push(val);
  }
  console.log("后", [...this.arr]);
  if(this.arr.length - this.k >= 0) {
    return this.arr[this.arr.length - this.k];
  } else {
    return this.arr[0];
  }

};

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
